package com.bw;


import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//123
//这里是读取文件
public class TestExcel {

    public static List<Map> read(String ext) throws Exception {

        //初始化一个excel文件的对象
        Workbook wb = null;

        List<Map> mapList = new ArrayList<>();
        //读取文件
        FileInputStream fileInputStream = new FileInputStream("D:\\用户数据.xlsx");

        //判断后缀名
        if (".xsl".equals(ext)){
            //根据后缀名进行获取excel文件的对象
            wb = new HSSFWorkbook(fileInputStream);
        }
        if (".xslx".equals(ext)){
            //根据后缀名进行获取excel文件的对象
            wb = new XSSFWorkbook(fileInputStream);
        }
        //获取文件中的sheet页的数据
        Sheet sheet = wb.getSheetAt(0);
        //获取最大行数就是行数
        int rowNum = sheet.getLastRowNum();
        //将行数进行循环
        for (int i=1;i<=rowNum;i++){
            System.out.println("这个是行数"+i);
            //获取具体行
            Row row = sheet.getRow(i);
            //获取具体列
            int cellNum = row.getLastCellNum();
            Map mapinfo = new HashMap();
            for (int j=0;j<cellNum;j++){
                //获取一列的数据
                Cell cell = row.getCell(j);
                //获取每行每列的数据，判断类型
                CellType cellType = cell.getCellTypeEnum();
                switch (cellType){
                    case STRING:
                        //获取行数为0的下标并且获取列的值
                        mapinfo.put(sheet.getRow(0).getCell(j).getStringCellValue(),cell.getStringCellValue());
                        break;
                    case BOOLEAN:
                        mapinfo.put(sheet.getRow(0).getCell(j).getStringCellValue(),cell.getBooleanCellValue());
                        break;
                    case BLANK:
                        mapinfo.put(sheet.getRow(0).getCell(j).getStringCellValue(),null);
                        break;
                    case ERROR:
                        mapinfo.put(sheet.getRow(0).getCell(j).getStringCellValue(),cell.getErrorCellValue());
                        break;
                    case NUMERIC:
                        if (HSSFDateUtil.isCellDateFormatted(cell)){
                            mapinfo.put(sheet.getRow(0).getCell(j).getStringCellValue(),cell.getDateCellValue());
                        }else {
                            mapinfo.put(sheet.getRow(0).getCell(j).getStringCellValue(),cell.getNumericCellValue());
                        }
                        break;
                }
            }
            mapList.add(mapinfo);
        }

        return mapList;
    }

    public static void main(String[] args) throws Exception {
        List<Map> read = read(".xslx");
        System.out.println(read);
    }
}
